package com.mmall.controller.portal;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by zyc on 7/1/17.
 */

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);


    @Autowired
    private IOrderService iOrderService;

    //支付接口
    @RequestMapping("/pay.do")
    @ResponseBody
    public ServerResponse pay(HttpSession session, Long orderNo, HttpServletRequest request) {

        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        //path 拿到的路径 upload 后面是没有/  ，所以在拼接URL 的时候得自己加上
        String path = request.getSession().getServletContext().getRealPath("upload");
        return iOrderService.pay(orderNo, user.getId(), path);
    }

    //支付宝回调接口----  支付宝调用这个接口 来告诉我们用户已经下单
    @RequestMapping("/alipay_callback.do")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request) {
        //从请求中获取 map
        Map requestParams = request.getParameterMap();

        Map<String, String> params = Maps.newHashMap();

        //创建 keySet的迭代器， 将对应的value 存入map中。动态的取出request里面的对象
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < valueStr.length(); i++) {
                //如果  i遍历到结尾  valueStr 就等于 该值 ，否则 用,隔开
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            System.out.println("回调传来的参数： " + name + "    " + valueStr);
            params.put(name, valueStr);
        }
        logger.info("支付宝回调, sign:{} ,trade_status :{} ,参数:{}", params.get("sign"), params.get("trade_status"), params.toString());
        System.out.println("支付宝回调具体参数：" + params.toString() + "*********************************************");

        // *********************************非常重要************************************
        // 验证回调是不是支付宝发的， 还要避免重复通知
        // 按照文档移除 signType
        params.remove("sign_type");
        params.remove("sign");
        //支付宝文档中 只移除了 sign
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
            if (!alipayRSACheckedV2) {
                return ServerResponse.createByErrorMessage("非法请求，验证不通过");
            }
        } catch (AlipayApiException e) {
            logger.error("支付宝验证回调异常", e);
        }
        //todo 验证各种数据
        System.out.println("开始调用 orderService 的 回调函数**********************************************");
        ServerResponse serverResponse = iOrderService.alipayCallback(params);
        System.out.println("结束调用 orderService 的 回调函数**********************************************");

        //再次提醒 支付宝发送回调函数， 成功场景的结果只认 success ，这个字符串。
        if (serverResponse.isSuccess()) {
            return Const.AlipayCallBack.RESPONSE_SUCCESS;
        }
        return Const.AlipayCallBack.RESPONSE_FAILED;
    }

    //查询订单状态
    @RequestMapping("/query_order_pay_status.do")
    @ResponseBody
    public ServerResponse queryOrderPayStatus(HttpSession session, Long orderNo) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        ServerResponse serverResponse = iOrderService.queryOrderPayStatus(user.getId(), orderNo);
        if (serverResponse.isSuccess()) {
            return ServerResponse.createBySuccess(true);
        }
        return ServerResponse.createBySuccess(false);
    }

    //创建订单
    @RequestMapping("/create.do")
    @ResponseBody
    //shippingId 收货地址
    public ServerResponse create(HttpSession session, Integer shippingId) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        //path 拿到的路径 upload 后面是没有/  ，所以在拼接URL 的时候得自己加上
        return iOrderService.createOrder(user.getId(), shippingId);

    }

    //取消订单
    @RequestMapping("/cancel.do")
    @ResponseBody
    public ServerResponse cancel(HttpSession session, Long orderNo) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        //path 拿到的路径 upload 后面是没有/  ，所以在拼接URL 的时候得自己加上
        return iOrderService.cancel(user.getId(), orderNo);

    }

    //查询购物车信息
    @RequestMapping("/get_order_cart_product.do")
    @ResponseBody
    public ServerResponse getOrderCartProduct(HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.getOrderCartProduct(user.getId());

    }

    @RequestMapping("/detail.do")
    @ResponseBody
    public ServerResponse detail(HttpSession session, Long orderNo) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.getOrderDetail(user.getId(), orderNo);
    }

    @RequestMapping("/list.do")
    @ResponseBody
    public ServerResponse list(HttpSession session, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.getOrderList(user.getId(), pageNum, pageSize);
    }


}

